<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\model\Admin;
use app\common\service\Token;
use app\common\traits\JumpTrait;

/**
 * 登录验证中间件
 */
class LoginMiddleware
{
    use JumpTrait;

    /**
     * @notes 登录验证
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');
        //判断接口是否免登录
        $isNotNeedLogin = $request->controllerObject->isNotNeedLogin();

        $adminInfo = [];

        $adminId = 0;
        // 需要登录
        if (!$isNotNeedLogin) {
            if (empty($token)) {
                return $this->fail('请求参数缺token', [], 400, 0);
            }

            $adminId = (new Token())->getToken($token, Token::TYPE_ADMIN);
            if (empty($adminId)) {
                return $this->fail('登录超时，请重新登录', [], 401);
            }

            // 获取用户信息
            $adminInfo = (new Admin())->find($adminId);
            if (empty($adminInfo)) {
                return $this->fail('登录超时，请重新登录', [], 401);
            }

            if ($adminInfo->status !== 1) {
                return $this->fail('用户已被禁用', [], 401);
            }

            if ($adminInfo->login_ip !== request()->ip()) {
                return $this->fail('登录环境异常，请重新登录', [], 401);
            }

            //token验证通过，自动续期
            $result = (new Token())->overtimeToken($token, Token::TYPE_ADMIN);
            if (!$result) {
                return $this->fail('登录超时，请重新登录', [], 401);
            }

            $adminInfo = $adminInfo->toArray();
        }

        //给request赋值，用于控制器
        $request->adminInfo = $adminInfo;
        $request->adminId = $adminId ?? 0;
        $request->token = $token ?? '';

        return $next($request);
    }
}